package com.example.springbootlearn.netty.okhttp;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.example.springbootlearn.netty.dto.BizMsg;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author：OBM
 * @DATE：2023/11/10 13:24
 */
@Slf4j
public class AsrWebsocketListener extends WebSocketListener {

    private final Map<WebSocket, Object> errorWebSockets = new ConcurrentHashMap<>();

    private final String sessionId;

    public AsrWebsocketListener(String sessionId) {
        this.sessionId = sessionId;
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        log.info("ASR_MMMM voice_id ===>{} 创建成功", sessionId);
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        log.info("voice_id ===>{} success xxx:{}", sessionId, text);

        BizMsg msgResp = JSON.parseObject(text, BizMsg.class);
        msgResp.setReceiverTime(DateUtil.now());
        log.info("voice_id ===>{} success:{}", sessionId, text);
//        St.send(msgResp.getMessageId(), msgResp);
    }


    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        log.info("voice_id ===>{} Closed code={} reason ={}", sessionId, code, reason);
        errorWebSockets.compute(webSocket, (ws, obj) -> {
            if (obj != null) {
                log.info("voice_id ===>{} websocket触发了onFailure方法还是会调用onClosed", sessionId);
            } else {
//                reduceOnlineAsrCount();
            }
            return null;
        });
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        log.info("voice_id ===>{} Failure Throwable {} response {}", sessionId, t.getMessage(), response);
//        if (errorWebSockets.putIfAbsent(webSocket, ERROR_OBJECT) == null) {
//            reduceOnlineAsrCount();
//            // 统计错误的次数
//            addFailAsrCount();
//            webSocket.close(1000, "Connection closed");
//        } else {
//            log.info("voice_id ===>{} 同一个websocket会多次触发方法", sessionId);
//        }
    }

}
